<template>
  <el-aside width="200px" class="sub-sidebar" v-show="visible">
    <!-- 搜索框 -->
    <div class="search-box">
      <el-input
        v-model="searchText"
        placeholder="Search..."
        :prefix-icon="Search"
        clearable />
    </div>

    <!-- 子菜单 -->
    <el-menu
      :default-active="activeSubMenu"
      class="sub-menu"
      router>
      <template v-if="mainMenu === 'dashboard'">
        <!-- 管理员显示所有菜单 -->
        <template v-if="userRole === 'ADMIN'">
          <el-menu-item v-for="item in filteredDashboardMenus"
            :key="item.type"
            :index="`/analysis/${item.type}`">
            <!-- <el-icon>
              <component :is="iconComponents[item.icon]" />
            </el-icon> -->
            <span>{{ item.name }}</span>
          </el-menu-item>
        </template>
        <template v-else>
          <!-- 普通用户只显示有权限的仪表板 -->
          <el-menu-item
            v-for="item in filteredDashboards"
            :key="item.type"
            :index="`/analysis/${item.type}`">
            <!-- <el-icon>
              <component :is="iconComponents[item.icon]" />
            </el-icon> -->
            <span>{{ item.name }}</span>
          </el-menu-item>
        </template>
      </template>
      <template v-if="mainMenu === 'permissions'">
        <el-menu-item
          v-for="dashboard in filteredDashboards"
          :key="dashboard.dashboardId"
          :index="`/permissions/dashboard/${dashboard.dashboardId}`">
          <!-- <el-icon>
            <component
              :is="iconComponents[dashboard.icon]"
              v-if="iconComponents[dashboard.icon]" />
          </el-icon> -->
          <span>{{ dashboard.name }}</span>
        </el-menu-item>
      </template>
      
    </el-menu>
  </el-aside>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getDashboardList } from '@/api/dashboard'
import {
  DataLine,
  ShoppingBag,
  User,
  Shop,
  Money,
  Document,
  Search
} from '@element-plus/icons-vue'

// 注册所有图标组件
const iconComponents = {
  DataLine,
  ShoppingBag,
  User,
  Shop,
  Money,
  Document
}

const props = defineProps({
  visible: Boolean,
  mainMenu: String
})

const router = useRouter()
const route = useRoute()
const searchText = ref('')
const dashboards = ref([])
const userRole = ref('')

// 预定义的仪表板菜单
const dashboardMenus = [
  { type: 'core', name: 'Core Data Analysis', icon: 'DataLine' },
  { type: 'product', name: 'Product Data Analysis', icon: 'ShoppingBag' },
  { type: 'customer', name: 'Customer Data Analysis', icon: 'User' },
  { type: 'shop', name: 'Shop Data Monitor', icon: 'Shop' },
  { type: 'income', name: 'Income Data Analysis', icon: 'Money' },
  { type: 'detail', name: 'Detailed Data Showcase', icon: 'Document' }
]


// 过滤后的仪表板菜单（管理员）
const filteredDashboardMenus = computed(() => {
  if (!searchText.value) return dashboards.value
  return dashboards.value.filter(d =>
    d.name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 过滤后的仪表板列表（普通用户和权限管理页面）
const filteredDashboards = computed(() => {
  if (!searchText.value) return dashboards.value
  return dashboards.value.filter(d =>
    d.name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 使用当前路由路径作为激活菜单项
const activeSubMenu = ref('/analysis')

// 获取仪表板列表
const fetchDashboards = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const data = await getDashboardList()
    // 如果是管理员，显示所有仪表板
    // 如果是普通用户，只显示有权限的仪表板
    let filteredData = []
    if (userInfo.role === 'ADMIN') {
      filteredData = data.map(d => ({
        type: d.dashboardType,
        name: d.dashboardName,
        icon: d.icon || 'DataLine',
        dashboardId: d.dashboardId
      }))
    } else {
      filteredData = data.filter(d => d.hasPermission)
        .map(d => ({
          type: d.dashboardType,
          name: d.dashboardName,
        }))
    }
    dashboards.value = filteredData
  } catch (error) {
  }
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  activeSubMenu.value = newPath
})

// 监听主菜单变化，当切换到权限管理时获取仪表板列表
watch(() => props.mainMenu, (newMenu) => {
  if (newMenu === 'permissions' || newMenu === 'dashboard') {
    fetchDashboards()
  }
})

onMounted(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  userRole.value = userInfo.role
  fetchDashboards()
})
</script>

<style scoped>
.sub-sidebar {
  background-color: #fff;
  height: 100vh;
  position: fixed;
  left: 200px;
  top: 0;
  width: 200px !important;
  border-right: 1px solid #eee;
  z-index: 900;
}

.search-box {
  padding: 16px;
}

.sub-menu {
  border-right: none;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  padding: 0 20px !important;
}

:deep(.el-menu-item.is-active) {
  background-color: #ECF5FE !important;
  border-radius: 4px;
  margin: 0 10px;
  width: calc(100% - 20px);
}

:deep(.el-menu-item:hover) {
  background-color: #ECF5FE !important;
  border-radius: 4px;
  margin: 0 10px;
  width: calc(100% - 20px);
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}
</style>